package com.zshlong.seckill.service;

import com.zshlong.seckill.mapper.OrderMapper;
import com.zshlong.seckill.pojo.OrderInfo;
import com.zshlong.seckill.pojo.SeckillOrder;
import com.zshlong.seckill.pojo.SeckillUser;
import com.zshlong.seckill.prefix.OrderKey;
import com.zshlong.seckill.util.RedisUtil;
import com.zshlong.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderService {
	
	@Autowired
	OrderMapper orderMapper;

	@Autowired
	RedisUtil redisUtil;

	// 查缓存是否有订单信息
	public SeckillOrder getSeckillOrderByUserIdGoodsId(long userId, long goodsId) {
//		return orderMapper.getSeckillOrderByUserIdGoodsId(userId, goodsId);
		return (SeckillOrder) redisUtil.get(OrderKey.getMiaoshaOrderByUidGid, ""+userId+"_"+goodsId);
	}

	public OrderInfo getOrderById(long orderId) {
		return orderMapper.getOrderById(orderId);
	}

	@Transactional
	public OrderInfo createOrder(SeckillUser user, GoodsVo goods) {
		// 创建订单
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setUserName(user.getNickname());
		orderInfo.setCreateDate(new Date());
		orderInfo.setDeliveryAddress(user.getDeliveryAddress());
		orderInfo.setGoodsCount(1);
		orderInfo.setGoodsId(goods.getId());
		orderInfo.setGoodsName(goods.getGoodsName());
		orderInfo.setGoodsPrice(goods.getSeckillPrice());
		orderInfo.setOrderChannel(1);
		orderInfo.setStatus(0);
		orderInfo.setUserId(user.getId());
		orderMapper.insert(orderInfo);

		// 创建秒杀订单
		SeckillOrder seckillOrder = new SeckillOrder();
		seckillOrder.setGoodsId(goods.getId());
		seckillOrder.setOrderId(orderInfo.getId());
		seckillOrder.setUserId(user.getId());
		orderMapper.insertSeckillOrder(seckillOrder);

		redisUtil.set(OrderKey.getMiaoshaOrderByUidGid, ""+user.getId()+"_"+goods.getId(), seckillOrder);

		return orderInfo;
	}

	public void deleteOrders() {
		orderMapper.deleteOrders();
		orderMapper.deleteSeckillOrders();
	}
}